package com.example.city_home_app.Activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.city_home_app.Bean.Down_Update;
import com.example.city_home_app.Fragment.Fragment_community;
import com.example.city_home_app.Fragment.Fragment_moment;
import com.example.city_home_app.Fragment.Fragment_news;
import com.example.city_home_app.Model.ApiModel;
import com.example.city_home_app.R;
import com.example.city_home_app.RetrofitListener;
import com.example.city_home_app.UI.ApkUpdateUtils;
import com.example.city_home_app.UI.MyHorizontalScrollView;
import com.example.city_home_app.UI.UIUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.shaohui.bottomdialog.BottomDialog;

public class MainActivity extends BaseActivity {

    @BindView(R.id.main_vp_content)
    FrameLayout content;
    @BindView(R.id.img_bottem_home)
    ImageView imgBottemHome;
    @BindView(R.id.tv_bottem_home)
    TextView tvBottemHome;
    @BindView(R.id.ll_bottem_home)
    LinearLayout llBottemHome;
    @BindView(R.id.img_bottem_community)
    ImageView imgBottemCommunity;
    @BindView(R.id.tv_bottem_community)
    TextView tvBottemCommunity;
    @BindView(R.id.ll_bottem_community)
    LinearLayout llBottemCommunity;
    @BindView(R.id.img_bottem_friend_circle)
    ImageView imgBottemFriendCircle;
    @BindView(R.id.tv_bottem_friend_circle)
    TextView tvBottemFriendCircle;
    @BindView(R.id.ll_bottem_friend_circle)
    LinearLayout llBottemFriendCircle;
    @BindView(R.id.hs)
    MyHorizontalScrollView hs;
    @BindView(R.id.img_main_toolbarsearch)
    ImageView imgMainToolbarsearch;
    @BindView(R.id.tv_mainmenu_msg)
    TextView tvMainmenuMsg;
    @BindView(R.id.tv_mainmenu_focus)
    TextView tvMainmenuFocus;
    @BindView(R.id.tv_mainmenu_post)
    TextView tvMainmenuPost;
    @BindView(R.id.tv_mainmenu_follow)
    TextView tvMainmenuFollow;
    @BindView(R.id.tv_mainmenu_edit)
    TextView tvMainmenuEdit;
    @BindView(R.id.menu)
    LinearLayout menu;

    private FragmentManager fragmentManager;
    private FragmentTransaction fragmentTransaction;
    private Fragment fragment_news, fragment_community, fragment_moment;
    private Toolbar toolbar;
    private boolean canClick = true;
    private int toolbarimg = 1;

    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;

    public static MainActivity instance;

    private RetrofitListener<Down_Update> listener = new RetrofitListener<Down_Update>() {
        @Override
        public void onResponse(final Down_Update listener) {
            if(!listener.getVersion_code().equals(ApkUpdateUtils.getVerName(MainActivity.this))){
                final AlertDialog.Builder normalDialog =
                        new AlertDialog.Builder(MainActivity.this);
                normalDialog.setTitle("更新通知");
                normalDialog.setMessage(listener.getVersion_intro());
                normalDialog.setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Uri uri = Uri.parse("http://siminzhang.top:8088/city_home_server/public/static/versions/"+listener.getVersion_file());
                                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                                startActivity(intent);
                            }
                        });
                normalDialog.setNegativeButton("关闭",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });
                // 显示
                normalDialog.show();
            }
        }

        @Override
        public void onFail(String msg) {

        }
    };

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initViews() {
        super.initViews();
        Window window = MainActivity.this.getWindow();
        //如果系统5.0以上
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(0xff49afcd);
        }
        ButterKnife.bind(this);
        showToast();
        hs.setstatus(false);
        instance = this;
    }

    @Override
    protected void initData() {
        super.initData();
        selectPage(0);

        ApiModel model = new ApiModel();
        model.getversion(listener);
        sharedPreferences = getSharedPreferences("Logininfo", Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();
    }

    @OnClick({R.id.ll_bottem_home, R.id.ll_bottem_community, R.id.ll_bottem_friend_circle, R.id.img_main_toolbarsearch,R.id.tv_mainmenu_msg, R.id.tv_mainmenu_focus, R.id.tv_mainmenu_post, R.id.tv_mainmenu_follow, R.id.tv_mainmenu_edit})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.ll_bottem_home:
                selectPage(0);
                break;
            case R.id.ll_bottem_community:
                selectPage(1);
                break;
            case R.id.ll_bottem_friend_circle:
                selectPage(2);
                break;
            case R.id.img_main_toolbarsearch:
                switch (toolbarimg) {
                    case 1:
                        break;
                    case 2:
                        intent = new Intent(this, PostAddActivity.class);
                        startActivity(intent);
                        break;
                    case 3:
                        intent = new Intent(this, MomentAddActivity.class);
                        startActivity(intent);
                        break;
                }
                break;
            case R.id.tv_mainmenu_msg:
                intent = new Intent(this,MessageCenterActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_mainmenu_focus:
                intent = new Intent(this,MyFocusActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_mainmenu_post:
                intent = new Intent(this,UserInfoActivity.class);
                intent.putExtra("id",BaseActivity.getUserinfo().getUserid());
                startActivity(intent);
                break;
            case R.id.tv_mainmenu_follow:
                intent = new Intent(this,MyLikeActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_mainmenu_edit:
                showeditdialog();
                break;
        }
    }


    private void selectPage(int select) {
        resetView();
        fragmentManager = getSupportFragmentManager();
        fragmentTransaction = fragmentManager.beginTransaction();
        hideFragment(fragmentTransaction);
        switch (select) {
            case 0:
                if (fragment_news == null) {
                    fragment_news = new Fragment_news();
                    fragmentTransaction.add(R.id.main_vp_content, fragment_news);
                } else {
                    fragmentTransaction.show(fragment_news);
                }
                imgBottemHome.setImageResource(R.drawable.ic_home_press);
                tvBottemHome.setTextColor(0xffF8F8FF);
                llBottemHome.setBackgroundColor(Color.parseColor("#5DB5D1"));
                toolbar.setTitle("你好," + BaseActivity.getUserinfo().getCityname());
                imgMainToolbarsearch.setVisibility(View.INVISIBLE);
                toolbarimg = 1;

                break;
            case 1:
                if (fragment_community == null) {
                    fragment_community = new Fragment_community();
                    fragmentTransaction.add(R.id.main_vp_content, fragment_community);
                } else {
                    fragmentTransaction.show(fragment_community);
                }
                imgBottemCommunity.setImageResource(R.drawable.ic_community_press);
                tvBottemCommunity.setTextColor(0xffF8F8FF);
                llBottemCommunity.setBackgroundColor(Color.parseColor("#5DB5D1"));
                toolbar.setTitle("社区中心");
                imgMainToolbarsearch.setVisibility(View.INVISIBLE);
                toolbarimg = 2;

                break;
            case 2:
                if (fragment_moment == null) {
                    fragment_moment = new Fragment_moment();
                    fragmentTransaction.add(R.id.main_vp_content, fragment_moment);
                } else {
                    fragmentTransaction.show(fragment_moment);
                }
                imgBottemFriendCircle.setImageResource(R.drawable.ic_friend_circle_press);
                tvBottemFriendCircle.setTextColor(0xffF8F8FF);
                llBottemFriendCircle.setBackgroundColor(Color.parseColor("#5DB5D1"));
                toolbar.setTitle("本地圈");
                imgMainToolbarsearch.setVisibility(View.VISIBLE);
                imgMainToolbarsearch.setImageResource(R.drawable.ic_add_moment);
                toolbarimg = 3;

                break;
        }
        fragmentTransaction.commit();
    }

    private void hideFragment(FragmentTransaction fragmentTransaction) {
        if (fragment_news != null) {
            fragmentTransaction.hide(fragment_news);
        }
        if (fragment_community != null) {
            fragmentTransaction.hide(fragment_community);
        }
        if (fragment_moment != null) {
            fragmentTransaction.hide(fragment_moment);
        }
    }

    private void resetView() {
        imgBottemHome.setImageResource(R.drawable.ic_home);
        imgBottemCommunity.setImageResource(R.drawable.ic_community);
        imgBottemFriendCircle.setImageResource(R.drawable.ic_friend_circle);

        tvBottemHome.setTextColor(0xff5C5C5C);
        tvBottemCommunity.setTextColor(0xff5C5C5C);
        tvBottemFriendCircle.setTextColor(0xff5C5C5C);

        llBottemCommunity.setBackgroundColor(Color.parseColor("#49afcd"));
        llBottemFriendCircle.setBackgroundColor(Color.parseColor("#49afcd"));
        llBottemHome.setBackgroundColor(Color.parseColor("#49afcd"));
    }

    private void showToast() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

        toolbar = (Toolbar) findViewById(R.id.toolbar_main);
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hs.move();
            }
        });

    }

    private void showeditdialog(){
        BottomDialog dialog;
        dialog = BottomDialog.create(getSupportFragmentManager());
        dialog.setViewListener(new BottomDialog.ViewListener() {
            @Override
            public void bindView(final View v) {
                final TextView edit = (TextView)v.findViewById(R.id.tv_editdialog_edit);
                final TextView exit = (TextView)v.findViewById(R.id.tv_editdialog_exit);
                edit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(MainActivity.this,EditActivity.class);
                        startActivity(intent);
                    }
                });

                exit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        editor.putString("LoginName", "");
                        editor.putString("LoginPassword", "");
                        editor.commit();
                        Intent intent = new Intent(MainActivity.this,LoginActivity.class);
                        startActivity(intent);
                        finish();
                    }
                });
            }
        })
                .setLayoutRes(R.layout.edit_dialog)
                .setDimAmount(0.1f)
                .setCancelOutside(true)
                .setTag("设置")
                .show();
    }


    private int back_count = 0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { //按下的如果是BACK，同时没有重复
            back_count++;
            if(back_count==2){
                finish();
            }else{
                backThread();
                UIUtils.showToast(this,"再按一次退出本程序",UIUtils.LENGTH_SHORT);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void backThread(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                    back_count--;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
